import hashlib
import time
from . import ConnPG
from .select_duty import SelectDuty

class Login:

    @staticmethod
    def generate_token(info_str):#生成一个token值

        hash_str = str(time.time()) + info_str

        result = hashlib.sha256(hash_str.encode()).hexdigest()

        return result

    async def add_token(self, token, user_id):#添加token值

        sql = "insert into token(user_id, token, token_time) values (%s, %s, %s)"
        await ConnPG().execute(sql, (user_id, token, int(time.time())))

    async def login(self, phone, password):#登录验证

        #数据检查
        if not all([phone, password]):

            return {
                'status': -1,
                'errorCode': 100102,
                'errorMsg': '手机或密码为空',
                'resultBody': None
            }
        
        sql = 'select id,name,phone from users where phone=%s and password=%s'

        result = await ConnPG().fetchone(sql, (phone, password))

        

        if result == None:

            return {
                'status': -1,
                'errorCode': 100103,
                'errorMsg': '请检查账号或密码',
                'resultBody': None
            }
        else:


            duty_info = await SelectDuty().select_duty_by_user_id(str(result['id']))

            token = self.generate_token(str(result))

            await self.add_token(token, result['id'])

            return {
                'status': 1,
                'errorCode': None,
                'errorMsg': None,
                'resultBody': {
                    "token": token,
                    "user_info": result,
                    "duty_info": duty_info['resultBody']
                }
            }